import { observable, action, makeAutoObservable, runInAction } from 'mobx'
import { findIndex, find, cloneDeep, remove } from 'lodash'

class RecordTime {
  constructor() {
    makeAutoObservable(this)
  }

  // 每个分屏的时间对象
  @observable timeArray = []

  @action addTimeArray(id, { duration, currentTime }) {
    runInAction(() => {
      const index = findIndex(this.timeArray, ['id', id])
      if (index !== -1) {
        this.timeArray.splice(index, 1)
      }
      this.timeArray.push({ id, currentTime, duration })
      const _timeArray = cloneDeep(this.timeArray)
      this.timeArray = []
      this.timeArray = _timeArray
    })
  }
  @action getTimeById(id) {
    return find(this.timeArray, ['id', id])
  }
  @action setTimeArray(id, str, val) {
    const time = find(this.timeArray, ['id', id])
    if (time) {
      time[str] = val
    }
  }
  @action exchangeId(dragId, dropId) {
    const { timeArray } = this
    const dragTime = find(timeArray, ['id', dragId])
    const dropTime = find(timeArray, ['id', dropId])
    if (dragTime) {
      dragTime.id = dropId
      if (dropTime) {
        dropTime.id = dragId
      }
    }
  }
  @action removeTimeArray(id) {
    remove(this.timeArray, ['id', id])
  }
}

export default new RecordTime()
